package com.cd.servlet;

import cn.hutool.json.JSONUtil;
import com.cd.dao.TVCategoryDao;
import com.cd.entity.TVCategory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/category")
public class TVCategoryServlet extends HttpServlet {
    private TVCategoryDao categoryDao;

    @Override
    public void init() throws ServletException {
        categoryDao = new TVCategoryDao();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        req.setCharacterEncoding("utf-8");

        String action = req.getParameter("action");
        if (action == null) {
            action = "list";
        }

        try {
            switch (action) {
                case "list":
                    // 查询所有分类
                    List<TVCategory> categoryList = categoryDao.findAll();
                    resp.getWriter().write(JSONUtil.toJsonStr(categoryList));
                    break;
                case "add":
                    // 添加分类
                    TVCategory category = new TVCategory();
                    category.setCategoryName(req.getParameter("categoryName"));
                    category.setCategoryDescription(req.getParameter("categoryDescription"));
                    int addResult = categoryDao.insert(category);
                    resp.getWriter().write("{\"result\":" + addResult + "}");
                    break;
                case "update":
                    // 更新分类
                    TVCategory updateCategory = new TVCategory();
                    updateCategory.setCategoryId(Integer.valueOf(req.getParameter("categoryId")));
                    updateCategory.setCategoryName(req.getParameter("categoryName"));
                    updateCategory.setCategoryDescription(req.getParameter("categoryDescription"));
                    int updateResult = categoryDao.update(updateCategory);
                    resp.getWriter().write("{\"result\":" + updateResult + "}");
                    break;
                case "delete":
                    // 删除分类
                    int categoryId = Integer.valueOf(req.getParameter("categoryId"));
                    int deleteResult = categoryDao.delete(categoryId);
                    resp.getWriter().write("{\"result\":" + deleteResult + "}");
                    break;
                default:
                    resp.getWriter().write("{\"error\":\"未知操作\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("{\"error\":\"服务器内部错误\"}");
        } finally {
            resp.getWriter().close();
        }
    }
}